<?php

class Comment extends CommentsAppModel
{
    var $name = 'Comment';
	var $validate = array(
						'body' =>array('rule'=>VALID_NOT_EMPTY,
						'message'=>'Body can\'t be empty'),
	);
	//$this->Comment->bindModel(array('belongsTo'=>array('Content'=>array('foreignKey'=>'item_id','conditions'=>'Comment.type="Content"')),array('User'=>array('className'=>'Users.User','foreignKey'=>'user_id','conditions'=>'Comment.type="Content"'))),false);
	var $belongsTo = array('User'=>array(
								'className'=>'Users.User',
								'foreignKey'=>'user_id'
							));

	/*array('belongsTo'=>array(
			
			User=>array(
						'className'=>'Users.User',
						'foreignKey'=>'user_id',
						'conditions'=>'Comment.type="Content"')
		))*/


	//var $actsAs = array('UserContent' => array('field'=>'status', 'moderation'=>'on'));
	function getComments($type, $item_id, $limit=null)
	{
		// User class name not good - may create a problem
		$this->bindModel(array('belongsTo' => array('User'=>array('className'=>'Users.User'))));
		$comments = $this->find('all',array('conditions'=>'Comment.type ="'.$type.'" AND Comment.item_id ='.$item_id,'order'=>'Comment.added asc', 'limit'=>$limit));
		return $comments;
	}

	function fetchComments($options=array())
	{
		$this->bindModel(array('belongsTo' => array('User'=>array('className'=>'Users.User'))));
		return $this->find('all',$options);
	}

	function beforeSave()
	{
		$path = APP.'plugins'.DS.'comments'.DS.'config'.DS.'bad_words.txt';
		$handle = fopen($path,'r');
		$contents = fread($handle,filesize($path));
		$badWordsArray = explode("\n",$contents);
		return $this->checkBadWords($badWordsArray);
	}

	function checkBadWords($badWordsArray)
	{
		uses('Flay');
		if(isset($this->data['Comment']['body']))
		{
			$comments = Flay::extractWords($this->data['Comment']['body']);
		}
		$comments =array();
		foreach($badWordsArray as &$word)
		{
			$word = trim($word);
		}
		foreach($comments as $comment)
		{
			if(array_search(low($comment),$badWordsArray)!==false)
			{
				$hasBadWords ='yes';
				return false;
			}
		}
		if(!isset($hasBadWords))
		{
			return true;

		}
	}	
}

?>